package cz.zcu.fav.ratdroid.activity;

import android.app.ListActivity;
import android.widget.Toast;
import cz.zcu.fav.ratdroid.service.IRestListener;
import cz.zcu.fav.ratdroid.service.RestTask;

/***
 * Basic skeleton class for all app list activities. Provides possibility to
 * communicate asynchronously with RAT server via REST services and also clean
 * up when main activity is cleaned ud (eg. during rotation)
 * 
 * @author Lukas Gemela
 * 
 * @param <T>
 */
public class SkeletonRestListActivity<T> extends ListActivity implements
		IRestListener<T>
{
	private RestTask<?> restTask;

	public synchronized RestTask<?> getRestTask()
	{
		return restTask;
	}

	/**
	 * set communication REST task.
	 * 
	 * @param restTask
	 */
	public synchronized void setRestTask(RestTask<?> restTask)
	{
		this.restTask = restTask;
	}

	@Override
	protected void onDestroy()
	{
		// clean rest task context
		if (getRestTask() != null)
		{
			getRestTask().setContext(null);
		}
		super.onDestroy();
	}

	/**
	 * default bahaviour - just clean up the task
	 */
	public void notifyDataLoaded(T data)
	{
		setRestTask(null);
	}

	public void notifyException(final Exception ex)
	{
		//in case of trouble just clean up task and show error toast
		setRestTask(null);
		runOnUiThread(new Runnable()
		{

			public void run()
			{
				Toast.makeText(getApplicationContext(),
						"Error eccured: " + ex.getMessage(), Toast.LENGTH_LONG)
						.show();
			}
		});

	}
}
